<style scoped>
#imageControl {
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
}
</style>
<template>
  <div id="app">
    <div id="imageControl">
      <img :src="imageUrl" :style="videoStyle" />
    </div>
  </div>
</template>
<script>
export default {
  props: {
    imageUrl: {
      type: String,
      default: ""
    },
    width: {
      type: String | Number,
      default: undefined
    },
    height: {
      type: String | Number,
      default: undefined
    }
  },
  data() {
    return {
      videoStyle: {
        width: "",
        height: ""
      },
      originWidth: undefined,
      originHeight: undefined
    };
  },
  watch: {
    width: {
      handler: function(newVal, oldVal) {
        this.resetSize();
      }
    },
    height: {
      handler: function(newVal, oldVal) {
        this.resetSize();
      }
    }
  },
  mounted() {
    // 获取当前组件宽度
    if (this.width) {
      this.originWidth = this.$el.getBoundingClientRect().width;
      this.originHeight = this.$el.getBoundingClientRect().width * (9 / 16);
      this.resetSize();
    }
    // 监听窗口变化
    const that = this;
    window.onresize = function temp() {
      that.checkFull();
      if (that.checkFull()) {
        if (that.width / window.innerWidth > that.height / window.innerHeight) {
          that.videoStyle.width = window.innerWidth + "px";
          that.videoStyle.height =
            (window.innerWidth * that.height) / that.width + "px";
        } else {
          that.videoStyle.height = window.innerHeight + "px";
          that.videoStyle.width =
            (window.innerHeight * that.width) / that.height + "px";
        }
      } else {
        that.resetSize();
      }
    };
  },
  methods: {
    resetSize() {
      if (this.width / this.originWidth > this.height / this.originHeight) {
        this.videoStyle.width = this.originWidth + "px";
        this.videoStyle.height =
          (this.originWidth * this.height) / this.width + "px";
      } else {
        this.videoStyle.height = this.originHeight + "px";
        this.videoStyle.width =
          (this.originHeight * this.width) / this.height + "px";
      }
    },
    checkFull() {
      let isFull =
        window.fullScreen ||
        document.webkitIsFullScreen ||
        document.msFullscreenEnabled;
      if (isFull === undefined) {
        isFull = false;
      }
      return isFull;
    }
  }
};
</script>
